package cn.edu.nuc.ssm.controller;

import cn.edu.nuc.ssm.entity.Admin;
import cn.edu.nuc.ssm.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping(value = "/admin")
public class BackAdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list() {

        return "back/admin/list";

    }
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String toadd(){

        return "back/admin/add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Admin admin, HttpSession session){

        Admin admin1 = adminService.findbyUsername(admin);

        if(admin1!=null){

            session.setAttribute("msg","用户名已经存在了");

            return "redirect:/admin/add";
        }

        adminService.insert(admin);

        return "redirect:/admin/list";
    }

    @ResponseBody
    @RequestMapping(value = "/listAdmin",method = RequestMethod.GET)
    public List<Admin> listAllAdmin(){

        List<Admin> adminList = adminService.find();

        return adminList;
    }

    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update( @RequestBody Admin admin){

        Admin admin1 = adminService.findbyUsername(admin);

        if(admin1!=null){

            return "error";
        }

         adminService.update(admin);
        return "success";
    }

    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public String delete(Integer id){

        adminService.delete(id);

        return "redirect:/admin/list";
    }

}
